package com.pl.lister;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.pl.entity.SysUser;
import com.pl.service.SysUserService;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @Author 小胤
 * @Date 2024/4/23 18:53
 * @注释
 */
public class SysUserReadLister extends AnalysisEventListener<SysUser> {
    //定义初始加入的记录数
    private static final int BATCH_COUNT=5;
    //引入SysUserService,后边导入会用到
    private SysUserService sysUserService;
    //创建初始集合存sysUser数据
    List<SysUser> sysUserList=new ArrayList<>();

    public SysUserReadLister() {
    }

    public SysUserReadLister(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    /**
     * 每调用一次 会回调此方法,该方法规定一次插入5条数据
     * @param sysUser
     * @param analysisContext
     */
    @Override
    public void invoke(SysUser sysUser, AnalysisContext analysisContext) {
        sysUserList.add(sysUser);
        if (sysUserList.size()>=BATCH_COUNT){
            saveDate();
            sysUserList.clear();
        }
    }

    private void saveDate() {
        System.out.println("开始批量导入");
        sysUserService.inserts(sysUserList);
        System.out.println("结束批量导入");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (sysUserList.size()>0){//最后一次存的地方
                saveDate();
            sysUserList.clear();
        }
    }
}
